package com.devunion.salon.persistence.dao;

import com.devunion.salon.persistence.GiftCard;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.io.Serializable;
import java.sql.SQLException;

/**
 * @author Viktar Liaskovich
 */
public class GiftCardDao extends BaseDaoObject<GiftCard>{
    public GiftCard getByKey(Serializable key) {
        return (GiftCard) getHibernateTemplate().get(GiftCard.class, key);
    }

    public GiftCard getCustomerGiftcard(final String giftcardNumber) {
        return (GiftCard) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                return session.createQuery("select trans.giftCard from Cheque cheque LEFT JOIN cheque.transactions trans " +
                        "where trans.giftCard.code = :giftcardNumber")                        
                        .setParameter("giftcardNumber", giftcardNumber, Hibernate.STRING)
                        .uniqueResult();                
            }
        });
    }
}